import {createRouter, createWebHistory} from 'vue-router'
import type {Router, RouteRecordRaw} from 'vue-router'
import {useMenuStore} from '@/stores/menu'
import pinia from '@/stores'

// 布局
const LayoutFrame = () => import('@/view/LayoutFrame.vue')

const Login = () => import('@/view/login/index.vue')
const Home = () => import('@/view/home/index.vue')

let routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/layout',
    name: 'layout',
    component: LayoutFrame,
    children: [
      {path: '/home', component: Home}
    ]
  }
]

let router: Router = createRouter({
  history: createWebHistory(),
  routes
})

let isAddRouter = false
let menuStore = useMenuStore()
router.beforeEach(async (to, from, next) => {
  if (!isAddRouter) {
    isAddRouter = true
    await menuStore.initMenuData()
    // 重新进入当前路由
    next({...to, replace: true})
  } else {
    next()
  }
})

export default router